import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class CouponStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  loading = false;
  company = [];
  prices = [];
  channelTypes = [];
  activitys = [];

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const res = yield api.search({ search, pg });
      // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
      const results = yield Promise.allSettled(res.map(async (p) => {
        try {
          const r = await api.getCouponCfg(p.id);
          return { ...p, rules: r?.decisionResults?.cfg?.result || {} };
        } catch (error) {
          return { ...p, error: true };
        }
      }));
      this.data = results.map((result) => ({
        ...result.value,
        rules: result.error ? {} : result.value.rules,
      }));
      return this.data;
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * update(coupon) {
    yield api.update(coupon);
    yield this.query();
  }

  * create(coupon) {
    yield api.create(coupon);
    yield this.query();
  }

  * remove(coupon) {
    yield api.remove(coupon.id);
    yield this.query();
  }

  * updateState(coupon) {
    yield api.update(coupon);
    yield this.query();
  }

  * getUserMobile(coupon) {
    const info = yield api.getUserMobile(coupon);
    return info;
  }

  * applyBatch(coupon) {
    yield api.applyBatch(coupon);
    yield this.query();
  }

  * getActivity(coupon) {
    const res = yield api.getActivity(coupon);
    const selectData = res.map((item) => ({
      label: item.name,
      value: item.id,
    }));
    this.activitys = selectData;
  }

  priceIdx(i, page, size) {
    return page * size + i + 1;
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get api() {
    return api;
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
